import { Route } from 'react-router-dom';
import { VFC, useState, useEffect } from 'react';
const Router: any = Route;
type RouterGuard = {
    before?: () => boolean | Promise<boolean>;
    // after?: () => boolean | Promise<boolean>;
    path: string;
    component: string | VFC | JSX.Element;
}

export const RouterGuard: VFC<RouterGuard> = (props) => {
    const [isLoaded, setIsLoaded] = useState(true);
    const [beforePass, setBeforePass] = useState(true);
    useEffect(() => {
        if(props.before) {
            setBeforePass(false);
            setIsLoaded(false);
            let before$ = props.before();
            // @ts-ignore
            if(before$.then === undefined) {
                before$ = Promise.resolve(before$);
            }
            (before$ as Promise<boolean>).then(res => {
                setBeforePass(res);
            })
            .finally(() => {
                setIsLoaded(true);
            });
        }
    }, []);
    const pass = (() => {
        let beforPass = props.before ? beforePass : true;
        return beforPass;
    })();
    if(isLoaded) {
        if(pass) {
            return (
                <Router exact  path={props.path} component={props.component}/>
            );
        } else {
            return <Router exact path={props.path} component={() => <>not pass</>}/>
        }
    }
    
    return <Router exact path={props.path} component={() => <>not pass</>} />
}

export function Dd () {
    return (<></>)
}